package com.lzx.iteam;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.*;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lzx.iteam.bean.ScheduleData;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetScheduleMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.provider.ScheduleDB;
import com.lzx.iteam.widget.selectdate.OnWheelScrollListener;
import com.lzx.iteam.widget.selectdate.WheelView;
import com.lzx.iteam.widget.selectdate.adapter.NumericWheelAdapter;
import com.lzx.iteam.util.DateUtil;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by Megan on 16/3/14.
 */
public class ScheduleCreateActivity extends Activity implements View.OnClickListener {

    private LinearLayout mLlBack;
    private TextView mTvTitle, mTvComplete, mTvTime, mTvEndTime, mTvRemind;
    private EditText mEtTheme, mEtAddress, mEtRemark;
    private ToggleButton mTbNotice, mTbLimit;
    private RelativeLayout mRlTimeLayout, mRlEndTimeLayout, mRlNotice, mRlRemind, mRlLimit;

    private PreferenceUtil mPreferenceUtil;

    private WheelView year;
    private WheelView month;
    private WheelView day;
    private WheelView hour;
    private WheelView mins;
    private int mStartYear, mEndYear;
    private int mStartMonth, mEndMonth;
    private int mStartDay, mEndDay;
    private int mStartHour, mEndHour;
    private int mStartMinute, mEndMinute;
    private int curYear;
    private int curMonth;
    private int curDate;
    private int curHour;
    private int curMinute;
    private long mStartTime;//开始时间
    private long mEndTime;//结束时间
    private long mAlertTime;//提醒时间 0.不提醒（默认）否则为其他时间戳

    private String eventId;
    private String mOldTime;//旧的开始时间

    private String mTitle;//主题
    private String mAddress;//地点
    private String mBossUid;//如果是自己发布则传0，否则（秘书操作老板的日程表）填写待接收人(boss)的user_id。
    private String mUpdate;//是否发送日程修改通知, 1.发送, 0.不发送(默认)
    private String mLimit;//是否仅自己可见, 1.仅自己可见  0.可见
    private String mRemark;//备注

    private PopupWindow mDateSelectPop;
    private PopupWindow mTimeRemindPop;
    private PopupWindow mTimeContinuePop;
    private Calendar c;
    private String mScheduleTime;
    private String mType;//1.日程，2.任务，3.xxx
    private ScheduleData scheduleData = new ScheduleData();
    private String mAction;
    private ScheduleDB mScheduleDb;
    private CloudDBOperation mCloudDBOperation;

    private static final int ADD_SCHEDULE_MSG = 1000;
    private static final int UPDATE_SCHEDULE_MSG = 1001;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ADD_SCHEDULE_MSG:
                    if (msg.arg1 == 0) {
                        ScheduleData data = (ScheduleData) msg.obj;
                        scheduleData.setId(data.getId());
                        scheduleData.setTitle(data.getTitle());
                        scheduleData.setPublishedUId(data.getPublishedUId());
                        String date = mStartYear + "_" + mStartMonth + "_" + mStartDay;
//                        mScheduleDb.addSchedule("1", date, scheduleData);
                        if (!"0".equals(scheduleData.getAlertTime())) {
                            mCloudDBOperation.insertAlarmWarnData(scheduleData);
                        }
                       /* Intent intent = new Intent(ScheduleCreateActivity.this, ScheduleCalendarActivity.class);
                        intent.putExtra("scheduleData", scheduleData);
                        startActivity(intent);*/
                        finish();
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(ScheduleCreateActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(ScheduleCreateActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case UPDATE_SCHEDULE_MSG:
                    if (msg.arg1 == 0) {
                        ScheduleDetailActivity.instance.finish();
                        finish();
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(ScheduleCreateActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(ScheduleCreateActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.schedule_create_layout);
        c = Calendar.getInstance();
        curYear = c.get(Calendar.YEAR);
        curMonth = c.get(Calendar.MONTH) + 1; //通过Calendar算出的月数要+1
        curDate = c.get(Calendar.DATE);
        curHour = c.get(Calendar.HOUR_OF_DAY);
        curMinute = c.get(Calendar.MINUTE);
        mScheduleDb = new ScheduleDB(this);
        mCloudDBOperation = new CloudDBOperation(this);

        mPreferenceUtil = PreferenceUtil.getInstance(ScheduleCreateActivity.this);
        initViews();
        getIntentData();

    }

    private void initViews() {
        mLlBack = (LinearLayout) this.findViewById(R.id.ll_schedule_create_back);
        mTvTitle = (TextView) this.findViewById(R.id.tv_schedule_create_title);
        mTvComplete = (TextView) this.findViewById(R.id.tv_schedule_create_complete);
        mTvTime = (TextView) this.findViewById(R.id.tv_schedule_create_time);
        mTvEndTime = (TextView) this.findViewById(R.id.tv_schedule_create_endtime);
        mTvRemind = (TextView) this.findViewById(R.id.tv_schedule_create_time_remind);
        mEtTheme = (EditText) this.findViewById(R.id.et_schedule_create_theme);
        mEtAddress = (EditText) this.findViewById(R.id.et_schedule_create_address);
        mEtRemark = (EditText) this.findViewById(R.id.et_schedule_create_time_remark);
        mTbNotice = (ToggleButton) this.findViewById(R.id.tb_schedule_create_notice);
        mTbLimit = (ToggleButton) this.findViewById(R.id.tb_schedule_create_limit);
        mRlTimeLayout = (RelativeLayout) this.findViewById(R.id.rl_schedule_create_time);
        mRlEndTimeLayout = (RelativeLayout) this.findViewById(R.id.rl_schedule_create_endtime);
        mRlNotice = (RelativeLayout) this.findViewById(R.id.rl_schedule_create_notice);
        mRlRemind = (RelativeLayout) this.findViewById(R.id.rl_schedule_create_time_remind);
        mRlLimit = (RelativeLayout) this.findViewById(R.id.rl_schedule_create_limit);

        mTbNotice.setChecked(false);
        mTbLimit.setChecked(false);
        mLlBack.setOnClickListener(this);
        mRlTimeLayout.setOnClickListener(this);
        mRlEndTimeLayout.setOnClickListener(this);
        mRlNotice.setOnClickListener(this);
        mRlLimit.setOnClickListener(this);
        mRlRemind.setOnClickListener(this);
        mTvComplete.setOnClickListener(this);
    }

    private void getIntentData() {
        Intent intent = getIntent();
        mAction = intent.getAction();
        ScheduleData scheduleData = (ScheduleData) intent.getSerializableExtra("scheduleData");
        if (intent.getBooleanExtra("isMe", true)) {
            mRlNotice.setVisibility(View.GONE);
            mRlLimit.setVisibility(View.VISIBLE);
        } else {
            mRlNotice.setVisibility(View.VISIBLE);
            mRlLimit.setVisibility(View.GONE);
        }
        if (scheduleData != null) {
            mTvTitle.setText("编辑");
            mBossUid = scheduleData.getBossUid();
            eventId = scheduleData.getId();
            mTitle = scheduleData.getTitle();
            mAddress = scheduleData.getAddress();
            mOldTime = scheduleData.getStartTime();
            mStartTime = Long.parseLong(scheduleData.getStartTime()) * 1000;
            mStartYear = DateUtil.getYear(mStartTime);
            mStartMonth = DateUtil.getMonth(mStartTime);
            mStartDay = DateUtil.getDay(mStartTime);
            mStartHour = DateUtil.getHour(mStartTime);
            mStartMinute = DateUtil.getMinute(mStartTime);
            if (!"0".equals(scheduleData.getEndTime())) {
                mEndTime = Long.parseLong(scheduleData.getEndTime()) * 1000;
                mEndYear = DateUtil.getYear(mEndTime);
                mEndMonth = DateUtil.getMonth(mEndTime);
                mEndDay = DateUtil.getDay(mEndTime);
                mEndHour = DateUtil.getHour(mEndTime);
                mEndMinute = DateUtil.getMinute(mEndTime);
                mTvEndTime.setText(DateUtil.getHourAndMin(mEndTime));
            }
            mAlertTime = Long.parseLong(scheduleData.getAlertTime()) * 1000;
            setNotice(scheduleData.getNotice());
            setLimit(scheduleData.getHidden());
            mRemark = scheduleData.getRemark();
            mEtTheme.setText(mTitle);
            mEtAddress.setText(mAddress);
            mEtRemark.setText(mRemark);
            mTvTime.setText(DateUtil.getAllTime(mStartTime));
            mTvRemind.setText(parseRemindTime(mAlertTime));
        } else {
            mBossUid = intent.getStringExtra("userId");
        }

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_schedule_create_back:
                finish();
                break;
            case R.id.rl_schedule_create_time:

                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(ScheduleCreateActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showDateSelectPop();
                break;
            case R.id.rl_schedule_create_endtime:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(ScheduleCreateActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (!StringUtil.isEmpty(mTvTime.getText().toString().trim())) {
                    showContinueDateSelectPop();
                } else {
                    Toast.makeText(this, "对不起，请先选择开始时间", Toast.LENGTH_LONG).show();
                }

                break;
            case R.id.rl_schedule_create_notice:
                mTbNotice.toggle();
                break;
            case R.id.rl_schedule_create_limit:
                mTbLimit.toggle();
                break;
            case R.id.rl_schedule_create_time_remind:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(ScheduleCreateActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showRemindTimePop();
                break;
            case R.id.tv_schedule_create_complete:
                if (StringUtil.isEmpty(mEtTheme.getText().toString().trim())) {
                    Toast.makeText(ScheduleCreateActivity.this, "对不起，主题不能为空", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    mTitle = mEtTheme.getText().toString().trim();
                }
                if (StringUtil.isEmpty(mTvTime.getText().toString().trim())) {
                    Toast.makeText(ScheduleCreateActivity.this, "对不起，开始时间不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (StringUtil.isEmpty(mTvEndTime.getText().toString().trim())) {
                    Toast.makeText(ScheduleCreateActivity.this, "对不起，结束时间不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                c.set(mStartYear, mStartMonth - 1, mStartDay, mEndHour, mEndMinute, 00);
                mEndTime = c.getTimeInMillis();
                if (mEndHour != 0 && mEndMinute != 0 && mEndTime < mStartTime) {
                    Toast.makeText(ScheduleCreateActivity.this, "结束时间小于开始时间，请重新选择", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mEndHour == 0 && mEndMinute == 0) {
                    mEndTime = 0;
                }

                if ("不提醒".equals(mTvRemind.getText().toString().trim())) {
                    mAlertTime = 0;
                } else if ("准时".equals(mTvRemind.getText().toString().trim())) {
                    mAlertTime = mStartTime;
                } else if ("10分钟".equals(mTvRemind.getText().toString().trim())) {
                    mAlertTime = mStartTime - addRemindTime(10);
                } else if ("30分钟".equals(mTvRemind.getText().toString().trim())) {
                    mAlertTime = mStartTime - addRemindTime(30);
                } else if ("1小时".equals(mTvRemind.getText().toString().trim())) {
                    mAlertTime = mStartTime - addRemindTime(60);
                } else if ("1天".equals(mTvRemind.getText().toString().trim())) {
                    mAlertTime = mStartTime - addRemindTime(60 * 24);
                }

                /*if (!StringUtil.isEmpty(mTvEndTime.getText().toString().trim())) {
                    if (mEndMonth != mStartMonth || mEndDay != mStartDay) {
                        Toast.makeText(ScheduleCreateActivity.this, "结束时间与开始时间不是同一天，请重新选择", Toast.LENGTH_LONG).show();
                        return;
                    } else if (!isOverStartTime()) {
                        Toast.makeText(ScheduleCreateActivity.this, "结束时间小于开始时间，请重新选择", Toast.LENGTH_LONG).show();
                        return;
                    }
                }*/
                mAddress = mEtAddress.getText().toString().trim();
                mRemark = mEtRemark.getText().toString().trim();
                if ("editSchedule".equals(mAction)) {
                    updateScheduleMsg();
                } else if ("createSchedule".equals(mAction)) {
                    addScheduleMsg();
                }

                break;
        }
    }

    private void setNotice(String notice) {
        if ("0".equals(notice)) {
            mTbNotice.setChecked(false);
        } else if ("1".equals(notice)) {
            mTbNotice.setChecked(true);
        }
    }

    private int getNotice() {//是否发送日程修改通知, 1.发送(默认), 0.不发送
        if (mTbNotice.isChecked()) {
            mUpdate = "1";
            return 1;
        } else {
            mUpdate = "0";
            return 0;
        }
    }

    private void setLimit(String limit) {
        if ("0".equals(limit)) {
            mTbLimit.setChecked(false);
        } else if ("1".equals(limit)) {
            mTbLimit.setChecked(true);
        }
    }


    private int getLimit() {//是否仅自己可见, 1.仅自己可见
        if (mTbLimit.isChecked()) {
            mLimit = "1";
            return 1;
        } else {
            mLimit = "0";
            return 0;
        }
    }

    /**
     * 选择提醒时间
     */
    public void showRemindTimePop() {
        final View view = LayoutInflater.from(this).inflate(R.layout.choose_remind_time_pop_layout, null);
        TextView remindNo = (TextView) view.findViewById(R.id.remind_time_no);
        TextView remindTime1 = (TextView) view.findViewById(R.id.remind_time1);
        TextView remindTime2 = (TextView) view.findViewById(R.id.remind_time2);
        TextView remindTime3 = (TextView) view.findViewById(R.id.remind_time3);
        TextView remindTime4 = (TextView) view.findViewById(R.id.remind_time4);
        TextView remindTime5 = (TextView) view.findViewById(R.id.remind_time5);
        remindNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTvRemind.setText("不提醒");
                mAlertTime = 0;
                mTimeRemindPop.dismiss();
            }
        });
        remindTime1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTvRemind.setText("准时");
                //  mAlertTime = mStartTime;
                mTimeRemindPop.dismiss();
            }
        });

        remindTime2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTvRemind.setText("10分钟");
                //  mAlertTime = mStartTime - addRemindTime(10);
                mTimeRemindPop.dismiss();
            }
        });
        remindTime3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTvRemind.setText("30分钟");
                //  mAlertTime = mStartTime - addRemindTime(30);
                mTimeRemindPop.dismiss();
            }
        });

        remindTime4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTvRemind.setText("1小时");
                // mAlertTime = mStartTime - addRemindTime(60);
                mTimeRemindPop.dismiss();
            }
        });

        remindTime5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTvRemind.setText("1天");
                //  mAlertTime = mStartTime - addRemindTime(60 * 24);
                mTimeRemindPop.dismiss();
            }
        });


        mTimeRemindPop = new PopupWindow(this);
        mTimeRemindPop.setBackgroundDrawable(new BitmapDrawable());
        mTimeRemindPop.setFocusable(true);
        mTimeRemindPop.setTouchable(true);
        mTimeRemindPop.setOutsideTouchable(true);
        mTimeRemindPop.setContentView(view);
        mTimeRemindPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mTimeRemindPop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        mTimeRemindPop.setAnimationStyle(R.style.bottomStyle);
        mTimeRemindPop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        mTimeRemindPop.update();
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mTimeRemindPop.dismiss();
                return false;
            }
        });

    }

    /**
     * 选择日期时间 pop
     */
    public void showDateSelectPop() {

        final View view = LayoutInflater.from(this).inflate(R.layout.select_date_pop_layout, null);

        year = (WheelView) view.findViewById(R.id.new_year);
        initYear(curYear);
        month = (WheelView) view.findViewById(R.id.new_month);
        initMonth();
        day = (WheelView) view.findViewById(R.id.new_day);
        initDay(curYear, curMonth);

        year.setCurrentItem(0);
        if (mStartMonth != 0) {
            month.setCurrentItem(mStartMonth - 1);
        } else {
            month.setCurrentItem(curMonth - 1);
        }
        if (mStartDay != 0) {
            day.setCurrentItem(mStartDay - 1);
        } else {
            day.setCurrentItem(curDate - 1);
        }

        hour = (WheelView) view.findViewById(R.id.new_hour);
        initHour();
        mins = (WheelView) view.findViewById(R.id.new_mins);
        initMins();
        // 设置当前时间
        if (mStartHour != 0) {
            hour.setCurrentItem(mStartHour);
        } else {
            hour.setCurrentItem(curHour);
        }
        int current = 0;
        if (mStartMinute != 0) {
            current = mStartMinute / 5;
        } else {
            current = curMinute / 5;
        }
        if (current == 11){
            mins.setCurrentItem(0);
        }else{
            mins.setCurrentItem(current + 1);
        }

        TextView bt = (TextView) view.findViewById(R.id.new_set);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mStartYear = year.getCurrentItem() + curYear;
                mStartMonth = month.getCurrentItem() + 1;
                mStartDay = day.getCurrentItem() + 1;
                mStartHour = hour.getCurrentItem();
                mStartMinute = mins.getCurrentItem() * 5;

                c.set(mStartYear, mStartMonth - 1, mStartDay, mStartHour, mStartMinute, 00);
                long selectTime = c.getTimeInMillis();
                mStartTime = selectTime;

                String date = mStartYear + "年" + mStartMonth + "月" + mStartDay + "日";
                String time = String.format("  %02d:%02d",mStartHour,mStartMinute);
                mScheduleTime = date + time;
                mTvTime.setText(mScheduleTime);


                mEndYear = mStartYear;
                mEndMonth = mStartMonth;
                if (mStartHour == 23) {
                    mEndDay = mStartDay+1;
                    mEndHour = 0;
                } else {
                    mEndDay = mStartDay;
                    mEndHour = hour.getCurrentItem() + 1;
                }
                mEndMinute = mins.getCurrentItem() * 5;

                c.set(mEndYear, mEndMonth - 1, mEndDay, mEndHour, mEndMinute, 00);
                mEndTime = c.getTimeInMillis();
                String endTime = String.format("%02d:%02d",mEndHour,mEndMinute);
                mTvEndTime.setText(endTime);
                mDateSelectPop.dismiss();
            }
        });
        TextView cancel = (TextView) view.findViewById(R.id.new_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDateSelectPop.dismiss();
            }
        });

        mDateSelectPop = new PopupWindow(this);
        mDateSelectPop.setBackgroundDrawable(new BitmapDrawable());
        mDateSelectPop.setFocusable(true);
        mDateSelectPop.setTouchable(true);
        mDateSelectPop.setOutsideTouchable(true);
        mDateSelectPop.setContentView(view);
        mDateSelectPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mDateSelectPop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        mDateSelectPop.setAnimationStyle(R.style.bottomStyle);
        mDateSelectPop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        mDateSelectPop.update();
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mDateSelectPop.dismiss();
                return false;
            }
        });
    }

    /**
     * 选择日期时间 pop
     */
    public void showEndDateSelectPop() {

        final View view = LayoutInflater.from(this).inflate(R.layout.select_time_pop_layout, null);

        hour = (WheelView) view.findViewById(R.id.new_hour);
        initHour();
        mins = (WheelView) view.findViewById(R.id.new_mins);
        initMins();
        // 设置当前时间
        if (mEndHour != 0) {
            hour.setCurrentItem(mEndHour);
        } else {
            hour.setCurrentItem(curHour);
        }
        if (mEndMinute != 0) {
            mins.setCurrentItem(mEndMinute / 5);
        } else {
            mins.setCurrentItem(curMinute / 5);
        }

        TextView bt = (TextView) view.findViewById(R.id.new_set);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEndHour = hour.getCurrentItem();
                mEndMinute = mins.getCurrentItem() * 5;
                if (mEndHour < mStartHour || (mEndHour == mStartHour && mEndMinute < mStartMinute)) {
                    Toast.makeText(ScheduleCreateActivity.this, "结束时间小于开始时间，请重新选择", Toast.LENGTH_LONG).show();
                    mEndHour = 0;
                    mEndMinute = 0;
                    mTvEndTime.setText("");
                } else {
                    String endTime = String.format("%02d:%02d",mEndHour,mEndMinute);
                    mTvEndTime.setText(endTime);
                }
                mDateSelectPop.dismiss();
            }
        });
        TextView cancel = (TextView) view.findViewById(R.id.new_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDateSelectPop.dismiss();
            }
        });

        mDateSelectPop = new PopupWindow(this);
        mDateSelectPop.setBackgroundDrawable(new BitmapDrawable());
        mDateSelectPop.setFocusable(true);
        mDateSelectPop.setTouchable(true);
        mDateSelectPop.setOutsideTouchable(true);
        mDateSelectPop.setContentView(view);
        mDateSelectPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mDateSelectPop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        mDateSelectPop.setAnimationStyle(R.style.bottomStyle);
        mDateSelectPop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        mDateSelectPop.update();
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mDateSelectPop.dismiss();
                return false;
            }
        });
    }

    /**
     * 快速显示结束时间
     * 持续时间
     * 选择其他弹出结束时间选择框
     */
    public void showContinueDateSelectPop() {
        final View view = LayoutInflater.from(this).inflate(R.layout.continue_time_pop_layout, null);
        LinearLayout layout = (LinearLayout) view.findViewById(R.id.select_time_ll);
        TextView continueTime1 = (TextView) view.findViewById(R.id.continue_time1);
        TextView continueTime2 = (TextView) view.findViewById(R.id.continue_time2);
        TextView continueTime3 = (TextView) view.findViewById(R.id.continue_time3);
        TextView continueTime4 = (TextView) view.findViewById(R.id.continue_time4);
        TextView continueTimeOther = (TextView) view.findViewById(R.id.continue_time_other);
        TextView continueTimeCancle = (TextView) view.findViewById(R.id.continue_time_cancle);
        continueTime1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEndTime = mStartTime + 30 * 60 * 1000;
                setEndTime();
                mTimeContinuePop.dismiss();
            }
        });
        continueTime2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEndTime=mStartTime+60*60*1000;
                setEndTime();
                mTimeContinuePop.dismiss();
            }
        });

        continueTime3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEndTime=mStartTime+120*60*1000;
                setEndTime();
                mTimeContinuePop.dismiss();
            }
        });
        continueTime4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEndTime=mStartTime+180*60*1000;
                setEndTime();
                mTimeContinuePop.dismiss();
            }
        });

        continueTimeOther.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showEndDateSelectPop();
                mTimeContinuePop.dismiss();
            }
        });

        continueTimeCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTimeContinuePop.dismiss();
            }
        });


        mTimeContinuePop = new PopupWindow(this);
        mTimeContinuePop.setBackgroundDrawable(new BitmapDrawable());
        mTimeContinuePop.setFocusable(true);
        mTimeContinuePop.setTouchable(true);
        mTimeContinuePop.setOutsideTouchable(true);
        mTimeContinuePop.setContentView(view);
        mTimeContinuePop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mTimeContinuePop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
//        mTimeContinuePop.setAnimationStyle(R.style.bottomStyle);
        layout.startAnimation(AnimationUtils.loadAnimation(ScheduleCreateActivity.this, R.anim.pop_translate_in));
        mTimeContinuePop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        mTimeContinuePop.update();
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mTimeContinuePop.dismiss();
                return false;
            }
        });
    }

    /**
     * 当年份和月份滑动结束，更新天数
     */
    OnWheelScrollListener scrollListener = new OnWheelScrollListener() {

        @Override
        public void onScrollingStarted(WheelView wheel) {

        }

        @Override
        public void onScrollingFinished(WheelView wheel) {
            // TODO Auto-generated method stub
//             int n_year = year.getCurrentItem() + 2015;// 楠烇拷
            int n_year = curYear;//
            int n_month = month.getCurrentItem() + 1;// 閺堬拷
            initDay(n_year, n_month);
        }
    };

    /**
     * @param year
     * @param month
     * @return
     */
    private int getDay(int year, int month) {
        int day = 30;
        boolean flag = false;
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            flag = true;
        }
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                day = 31;
                break;
            case 2:
                day = flag ? 29 : 28;
                break;
            default:
                day = 30;
                break;
        }
        return day;
    }

    /**
     * 初始化年
     */
    private void initYear(int curYear) {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, curYear, curYear + 1);
        numericWheelAdapter.setLabel(" 年");
        //		numericWheelAdapter.setTextSize(15);  设置字体大小
        year.setViewAdapter(numericWheelAdapter);
        year.setCyclic(false);
    }

    /**
     * 初始化月
     */
    private void initMonth() {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, 1, 12, "%02d");
        numericWheelAdapter.setLabel(" 月");
        //		numericWheelAdapter.setTextSize(15);  设置字体大小
        month.setViewAdapter(numericWheelAdapter);
        month.setCyclic(true);
        month.addScrollingListener(scrollListener);
    }

    /**
     * 初始化天
     */
    private void initDay(int arg1, int arg2) {
        int count = getDay(arg1, arg2);
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, 1, count, "%02d");
        numericWheelAdapter.setLabel(" 日");
        //		numericWheelAdapter.setTextSize(15);  设置字体大小
        day.setViewAdapter(numericWheelAdapter);
        day.setCyclic(true);
        // TODO 如果之前选择的日期大于这个月的天数 置为第一天
        if (day.getCurrentItem() + 1 > count) {
            day.setCurrentItem(0);
        }
    }

    /**
     * 初始化时
     */
    private void initHour() {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, 0, 23, "%02d");
        numericWheelAdapter.setLabel(" 时");
        //		numericWheelAdapter.setTextSize(15);  设置字体大小
        hour.setViewAdapter(numericWheelAdapter);
        hour.setCyclic(true);
    }

    /**
     * 初始化分
     */
    private void initMins() {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, 0, 11, "%02d", 5);
        numericWheelAdapter.setLabel(" 分");
//		numericWheelAdapter.setTextSize(15);  设置字体大小
        mins.setViewAdapter(numericWheelAdapter);
        mins.setCyclic(true);
    }

    private boolean isOverTime() {
        long curTime = System.currentTimeMillis();
        // 注意月份的加减
        c.set(mStartYear, mStartMonth - 1, mStartDay, mStartHour, mStartMinute, 00);
        long selectTime = c.getTimeInMillis();

        /*String cur = DateUtil.getDetailDate(curTime);
        String se = DateUtil.getDetailDate(selectTime);
        Log.d("Cur_time", mYear+"nian" + mMonth+"yue" + mDay+"ri" + mHour+"shi" + mMinute+"fen");
        Log.d("Cur_time", curTime + "  *********  " + selectTime);
        Log.d("Cur_time", cur + "  *********  " + se);*/

        if (selectTime > curTime) {
            mStartTime = selectTime;
            return true;
        } else {
            return false;
        }

    }

    /**
     * 创建日程
     */
    private void addScheduleMsg() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_TYPE, "1"));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_TITLE, mTitle));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ADDRESS, mAddress));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_BOSS_UID, mBossUid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_START_DATETIME, mStartTime / 1000 + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_END_DATETIME, mEndTime / 1000 + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ALERT_DATETIME, mAlertTime / 1000 + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_UPDATE, getNotice() + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_HIDDEN, getLimit() + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_REMARK, mRemark));
        if ("0".equals(mBossUid)) {
            scheduleData.setPublishedUId(mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1"));
        } else {
            scheduleData.setPublishedUId(mBossUid);
        }
        scheduleData.setType(mType);
        scheduleData.setNotice(mUpdate);
        scheduleData.setHidden(mLimit);
        scheduleData.setAlertTime(mAlertTime / 1000 + "");
        scheduleData.setStartTime(mStartTime / 1000 + "");

        scheduleData.setEndTime(mEndTime / 1000 + "");
        scheduleData.setCreateTime(System.currentTimeMillis() / 1000 + "");
        scheduleData.setRemark(mRemark);
        GetScheduleMsg scheduleMsg = new GetScheduleMsg(mHandler.obtainMessage(ADD_SCHEDULE_MSG), this);
        scheduleMsg.mApi = AsynHttpClient.API_EVENT_CALENDAR_ADD;
        scheduleMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(scheduleMsg);

    }

    /**
     * 更新日程
     */
    private void updateScheduleMsg() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ID, eventId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_TITLE, mTitle));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ADDRESS, mAddress));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_BOSS_UID, mBossUid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_OLD_START_DATETIME, mOldTime));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_NEW_START_DATETIME, mStartTime / 1000 + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_END_DATETIME, mEndTime / 1000 + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ALERT_DATETIME, mAlertTime / 1000 + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_UPDATE, getNotice() + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_HIDDEN, getLimit() + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_REMARK, mRemark));
       /* if ("0".equals(mUserId)) {
            scheduleData.setPublishedUId(mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1"));
        } else {*/
        scheduleData.setPublishedUId(mBossUid);
        //}
        scheduleData.setType(mType);
        scheduleData.setNotice(mUpdate);
        scheduleData.setHidden(mLimit);
        scheduleData.setAlertTime(mAlertTime / 1000 + "");
        scheduleData.setStartTime(mStartTime / 1000 + "");
        scheduleData.setEndTime(mEndTime / 1000 + "");
        scheduleData.setCreateTime(System.currentTimeMillis() / 1000 + "");
        scheduleData.setRemark(mRemark);
        GetScheduleMsg scheduleMsg = new GetScheduleMsg(mHandler.obtainMessage(UPDATE_SCHEDULE_MSG), this);
        scheduleMsg.mApi = AsynHttpClient.API_EVENT_CALENDAR_UPDATE;
        scheduleMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(scheduleMsg);

    }

    private long addRemindTime(int time) {
        return time * 60 * 1000;
    }

    private String parseRemindTime(long time) {
        if (time == 0) {
            return "不提醒";
        } else if (mStartTime == time) {
            return "准时";
        } else if ((mStartTime - time) / 1000 / 60 == 60) {
            return "1小时";
        } else if ((mStartTime - time) / 1000 / 60 == 60 * 24) {
            return "1天";
        } else {
            return ((mStartTime - time) / 1000 / 60) + "分钟";
        }
    }


    private void setEndTime(){
        mEndYear = DateUtil.getYear(mEndTime);
        mEndMonth = DateUtil.getMonth(mEndTime);
        mEndDay = DateUtil.getDay(mEndTime);
        mEndHour = DateUtil.getHour(mEndTime);
        mEndMinute = DateUtil.getMinute(mEndTime);
        mTvEndTime.setText(DateUtil.getHourAndMin(mEndTime));
    }

}
